package vikaa.timelinepackage;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import com.vikaa.pullview.PullToRefreshView;
import com.vikaa.pullview.PullToRefreshView.OnFooterRefreshListener;
import com.vikaa.pullview.PullToRefreshView.OnHeaderRefreshListener;

import vikaa.bean.File_item;
import vikaa.bean.TwitterHash;
import vikaa.tools.CalendarUtil;
import vikaa.tools.HttpUtil;
import vikaa.tools.ValueClass;
import vikaa.ui.ChoosePhotoList;
import vikaa.ui.ChoosePhotoUpload;
import vikaa.ui.Mywowo;
import vikaa.wowo.R;
import vikaa.wowo.cache.TwitterSqlStoragePrivate;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class TimelineGallery extends Activity implements OnHeaderRefreshListener,OnFooterRefreshListener,OnItemClickListener{
	private LinearLayout backBtn;
	private ImageView submitBtn;
	private GridView mGridView;
	private PullToRefreshView mPullToRefreshView;
	private AdapterGallery adapter;
	private int page;
	public static String space_id;
	public static String role;
	private ArrayList<TwitterHash> oldList ;
	private ArrayList<File_item> photolist ;
	public ImageView libraryBtn;
	public static boolean isrefresh = false;
	private LinearLayout header;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.timeline_gallery);
		space_id = getIntent().getExtras().getString("space_id");
		role = getIntent().getExtras().getString("role");
		page = 1;
		photolist = new ArrayList<File_item>();
		initview();
		new GetAlreadyTimelineThread(space_id).start();
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(isrefresh){
			isrefresh = false;
			photolist.addAll(ChoosePhotoUpload.uplist);
			adapter.notifyDataSetChanged();
		}
	}
	private void initview(){
		header = (LinearLayout)findViewById(R.id.header);
		libraryBtn =(ImageView)findViewById(R.id.uploadBtn);
		libraryBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				startActivity(new Intent(TimelineGallery.this,ChoosePhotoList.class));
			}
		});
		backBtn = (LinearLayout)findViewById(R.id.backBtn);
		backBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
				TwitterSqlStoragePrivate.dropfilechoosed(getApplicationContext());
				TwitterSqlStoragePrivate.dropRemoveTwitter(getApplicationContext());
			}
		});
		submitBtn = (ImageView)findViewById(R.id.submitBtn);
		submitBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				try{
					ArrayList<File_item> addList = TwitterSqlStoragePrivate.getfilechoosedTwitterFromSql(getApplicationContext());
					ArrayList<String> romoveList = TwitterSqlStoragePrivate.getRemoveListFromSql(getApplicationContext());
					JSONArray removeTwitters = new JSONArray();
					JSONArray addTwitters = new JSONArray();
					if(addList.size() >0 || romoveList.size()>0){
						for(String hash:romoveList){
							removeTwitters.put(hash);
						}
						for(File_item item:addList){
							addTwitters.put(item.getFile_id());
						}
						new UpdateTwitterThread(addTwitters.toString(), removeTwitters.toString(), space_id).start();
					}
					else
						Toast.makeText(getApplicationContext(), "choose photo", Toast.LENGTH_SHORT).show();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		});
		mPullToRefreshView = (PullToRefreshView)findViewById(R.id.main_pull_refresh_view);
		mGridView = (GridView)findViewById(R.id.gridview);
		adapter = new AdapterGallery(TimelineGallery.this, getLayoutInflater(), photolist);
		mGridView.setAdapter(adapter);
		mGridView.setOnItemClickListener(this);
        mPullToRefreshView.setOnHeaderRefreshListener(this);
        mPullToRefreshView.setOnFooterRefreshListener(this);
	}
	Handler mhandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
			case 1:
				new GetFileThread(space_id, String.valueOf(page)).start();
				break;
			case 2:
				//DialogService.closeProgressDialog();
				header.setVisibility(View.GONE);
				if(msg.obj != null){
					ArrayList<File_item> strings = (ArrayList<File_item>) msg.obj;
					if(!strings.isEmpty()){
						photolist.addAll(strings);
						adapter.notifyDataSetChanged();
					}
				}
				break;
			case 3:
				//DialogService.closeProgressDialog();
				header.setVisibility(View.GONE);
				//Toast.makeText(TimelineGallery.this, (String)msg.obj, Toast.LENGTH_SHORT).show();
				break;
			case 4:
				//DialogService.closeProgressDialog();
				header.setVisibility(View.GONE);
				Toast.makeText(TimelineGallery.this, R.string.network_crash, Toast.LENGTH_SHORT).show();
				break;
			case 5:
				//DialogService.closeProgressDialog();
				header.setVisibility(View.GONE);
				//Toast.makeText(TimelineGallery.this, "no twitters", Toast.LENGTH_SHORT).show();
				break;
			case 6:
				TwitterSqlStoragePrivate.dropfilelistTwitter(getApplicationContext());
				TwitterSqlStoragePrivate.dropfilechoosed(getApplicationContext());
				TwitterSqlStoragePrivate.dropRemoveTwitter(getApplicationContext());
				finish();
				Timeline.isimport = true;
				Mywowo.isrefresh = true;
				break;
			}
		}
	};
	private boolean hashMatch(String hash){
		if(oldList.size()>0){
			for(TwitterHash th:oldList){
				if(hash.equals(th.getHash())){
					return true;
				}
			}
		}
		return false;
	}
	class GetAlreadyTimelineThread extends Thread{
		private String space_id;
		private boolean isrun = true;
		public GetAlreadyTimelineThread(String space_id) {
			super();
			this.space_id = space_id;
		}
		@Override
		public void run() {
			super.run();
			while(isrun){
				oldList = new ArrayList<TwitterHash>();
				isrun  = false;
				try{
					Map<String, String> map = new HashMap<String, String>();
					map.put("space_id", space_id);
					JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(HttpUtil.BASE_URL+"space/TwitterList", map));
					if(jsonObj.getString("result").equals("1")){
						JSONObject info = jsonObj.getJSONObject("info");
						Iterator it = info.keys();  
						while (it.hasNext()) {  
							TwitterHash th = new TwitterHash();
				            String key = it.next().toString(); 
				            th.setHash(key);
				            th.setState(info.getString(key));
				            oldList.add(th);
						}
						Message msg = mhandler.obtainMessage(1);
						msg.sendToTarget();
						 //TwitterSqlStoragePrivate.SaveHashlistInSql(oldList, getApplicationContext());
					}
					else if(jsonObj.getString("result").equals("0")){
						Message msg = mhandler.obtainMessage(3);
						msg.obj = jsonObj.getString("msg");
						msg.sendToTarget();
					}
					else{
						Message msg = mhandler.obtainMessage(4);
						msg.sendToTarget();
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}
	class GetFileThread extends Thread{
		private String space_id;
		private String page;
		private boolean isrun = true;
		public GetFileThread(String space_id,
				String page) {
			super();
			this.space_id = space_id;
			this.page = page;
		}
		@Override
		public void run() {
			super.run();
			while(isrun){
				isrun  = false;
				try{
					Map<String, String> map = new HashMap<String, String>();
					map.put("space_id", space_id);
					map.put("page", page);
					JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(HttpUtil.BASE_URL+"file/uploadList", map));
					if(jsonObj.getString("result").equals("1")){
						JSONArray info = jsonObj.getJSONArray("info");
						ArrayList<File_item> tempList = new ArrayList<File_item>();
						for(int i=0;i<info.length();i++){
							File_item item = new File_item();
							item.setDateline(info.getJSONObject(i).getString("dateline"));
							item.setFile_id(info.getJSONObject(i).getString("file_id"));
							item.setThumbnail(info.getJSONObject(i).getString("thumbnail"));
							item.setHash(info.getJSONObject(i).getString("hash"));
							if(hashMatch(item.getHash())){
								item.setSelected(true);
								item.setUploaded(true);
							}else{
								item.setSelected(false);
								item.setUploaded(false);
							}
							tempList.add(item);
						}
						Message msg = mhandler.obtainMessage(2);
						//TwitterSqlStoragePrivate.SaveFilelistInSql(tempList, getApplicationContext());
						msg.obj = tempList;
						msg.sendToTarget();
					}
					else if(jsonObj.getString("result").equals("0")){
						Message msg = mhandler.obtainMessage(3);
						msg.obj = jsonObj.getString("msg");
						msg.sendToTarget();
					}
					else{
						Message msg = mhandler.obtainMessage(4);
						msg.sendToTarget();
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}
	class UpdateTwitterThread extends Thread{
		private String addTwitters;
		private String removeTwitters;
		private String space_id;
		private boolean isrun=true;
		public UpdateTwitterThread(String addTwitters, String removeTwitters,
				String space_id) {
			super();
			this.addTwitters = addTwitters;
			this.removeTwitters = removeTwitters;
			this.space_id = space_id;
		}
		@Override
		public void run() {
			while(isrun){
				isrun = false;
				Map<String, String> map = new HashMap<String, String>();
				map.put("space_id", space_id);
				map.put("addFiles", addTwitters);
				map.put("removeTwitters", removeTwitters);
				try{
					JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(HttpUtil.BASE_URL+"twitter/spacetwitterchange", map));
					if(jsonObj.getString("result").equals("1")){
						Message msg = mhandler.obtainMessage(6);
						msg.sendToTarget();
					}
					else if(jsonObj.getString("result").equals("0")){
						Message msg = mhandler.obtainMessage(3);
						msg.obj = jsonObj.getString("msg");
						msg.sendToTarget();
					}
					else{
						Message msg = mhandler.obtainMessage(4);
						msg.sendToTarget();
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}
	public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
		if(!(photolist.get(position).isUploaded())){
			if(!(photolist.get(position).isSelected()) )
				TwitterSqlStoragePrivate.savefileChoosedinSql(photolist.get(position), getApplicationContext());
			else
				TwitterSqlStoragePrivate.delectfileChoosedinSql(photolist.get(position), getApplicationContext());
		}
		else{
			if(photolist.get(position).isSelected())
				TwitterSqlStoragePrivate.saveRemoveList(photolist.get(position).getHash(), getApplicationContext());
			else
				TwitterSqlStoragePrivate.delectRemoveList(photolist.get(position).getHash(), getApplicationContext());
		}
		adapter.changeState(position,view);
	}
	public void onFooterRefresh(PullToRefreshView view) {
		page++;
		new GetFileThread(space_id, String.valueOf(page)).start();
		mPullToRefreshView.postDelayed(new Runnable() {
			public void run() {
				mPullToRefreshView.onFooterRefreshComplete();
			}
		},5000);
	}
	public void onHeaderRefresh(PullToRefreshView view) {
		
		mPullToRefreshView.postDelayed(new Runnable() {
			public void run() {
				mPullToRefreshView.onHeaderRefreshComplete("更新于:"+ CalendarUtil.Date2String(Calendar.getInstance().getTime(), ValueClass.PULL_REFRESH_TIME));
			}
		},2000);
	}
	
}
